package com.cloudspace.yunloan.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.cloudspace.yunloan.R;
import com.cloudspace.yunloan.YunloanApp;
import com.cloudspace.yunloan.activity.CaseActivity;
import com.cloudspace.yunloan.activity.YunloanBaseActivity;
import com.cloudspace.yunloan.constants.Constants;
import com.cloudspace.yunloan.entity.BaseResult;
import com.cloudspace.yunloan.entity.CaseEntity;
import com.cloudspace.yunloan.entity.PicCheckResult;
import com.cloudspace.yunloan.manager.HeadphotoManager;
import com.cloudspace.yunloan.net.manager.ImageManager;
import com.cloudspace.yunloan.network.JsonCallBack;
import com.cloudspace.yunloan.network.api.API;
import com.cloudspace.yunloan.utils.AppPreferences;
import com.cloudspace.yunloan.utils.BitmapUtil;
import com.cloudspace.yunloan.utils.FileUtil;
import com.cloudspace.yunloan.utils.IdCardUtil;
import com.cloudspace.yunloan.utils.MMAlert;
import com.cloudspace.yunloan.utils.ToastMaker;
import com.cloudspace.yunloan.utils.Utility;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

import static com.cloudspace.yunloan.activity.CaseActivity.INDEX_SIGN;

public class CardValidFragment extends BaseFragment implements View.OnClickListener {
    private View rootView;

    private String personalImg1Path;
    private String personalImg2Path;
    private String personalImg3Path;

    private ImageView personalImg1;
    private ImageView personalImg2;
    private ImageView personalImg3;

    private EditText identityCardEt;
    private EditText nameEt;

    private View cardFrontV;
    private View cardBackV;
    private View cardPersonV;

    private HeadphotoManager headphotoManager;
    private int photoTakeState;

    private int STATE_FRONT = 0;
    private int STATE_BACK = 1;
    private int STATE_PERSON = 2;
    private View nextStepTv;
    private View compareTv;

    private boolean compareSuccess;
    private CaseEntity mCaseEntity;

    private float compareScore;

    private static final int BITMAP_WIDTH = 528;
    private static final int BITMAP_HEIGHT = 314;



    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_card_valid, container, false);

        identityCardEt = rootView.findViewById(R.id.id_card_et);
        nameEt = rootView.findViewById(R.id.id_user_name);

        cardFrontV = rootView.findViewById(R.id.card_front_rl);
        cardBackV = rootView.findViewById(R.id.card_back_rl);
        cardPersonV = rootView.findViewById(R.id.person_photo_rl);

        cardFrontV.setOnClickListener(this);
        cardBackV.setOnClickListener(this);
        cardPersonV.setOnClickListener(this);

        personalImg1 = rootView.findViewById(R.id.auth_img1);
        personalImg2 = rootView.findViewById(R.id.auth_img2);
        personalImg3 = rootView.findViewById(R.id.auth_img3);

        headphotoManager = new HeadphotoManager((YunloanBaseActivity) getActivity());
        headphotoManager.setOnHeadphotoCropListener(new HeadphotoManager.OnHeadphotoCropListener() {
            @Override
            public void headphotoCroped(File file) {
                if (photoTakeState == STATE_FRONT) {
                    try {
                        BitmapUtil.compressImage(getActivity(), file.getPath(), BITMAP_WIDTH, BITMAP_HEIGHT, new File(FileUtil.getAuthPhotoPath() + "/" +  Constants.AUTH_REALNAME_PIC1), 50);
                        personalImg1Path = Utility.getRealNameAuthImage1Path();
                        ImageManager.loadImage(YunloanApp.getInstance(), personalImg1, personalImg1Path);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                } else if (photoTakeState == STATE_BACK) {
                    try {
                        BitmapUtil.compressImage(getActivity(), file.getPath(), BITMAP_WIDTH, BITMAP_HEIGHT, new File(FileUtil.getAuthPhotoPath() + "/" +  Constants.AUTH_REALNAME_PIC2), 50);
                        personalImg2Path = Utility.getRealNameAuthImage2Path();
                        ImageManager.loadImage(YunloanApp.getInstance(), personalImg2, personalImg2Path);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                } else if (photoTakeState == STATE_PERSON) {
                    try {
                        BitmapUtil.compressImage(getActivity(), file.getPath(), BITMAP_WIDTH, BITMAP_HEIGHT, new File(FileUtil.getAuthPhotoPath() + "/" +  Constants.AUTH_REALNAME_PIC3), 50);
                        personalImg3Path = Utility.getRealNameAuthImage3Path();
                        ImageManager.loadImage(YunloanApp.getInstance(), personalImg3, personalImg3Path);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                FileUtil.deleteFile(file);
            }
        });

        nextStepTv = rootView.findViewById(R.id.next_step_tv);
        nextStepTv.setOnClickListener(this);

        compareTv = rootView.findViewById(R.id.compare_tv);
        compareTv.setOnClickListener(this);


        if (mCaseEntity != null) {
            //从未完成列表过来，更新数据
            if (!TextUtils.isEmpty(mCaseEntity.idCard)) {
                identityCardEt.setText(mCaseEntity.idCard);
            }

            ImageManager.loadImage(getActivity(), personalImg1, mCaseEntity.idFrontImgUrl);
            ImageManager.loadImage(getActivity(), personalImg2, mCaseEntity.idBackImgUrl);
            ImageManager.loadImage(getActivity(), personalImg3, mCaseEntity.idPersonImgUrl);

            if (mCaseEntity.state == 2) {
                //不能更改这些信息
                nextStepTv.setVisibility(View.GONE);
                compareTv.setVisibility(View.GONE);
            }
        }

        return rootView;
    }

    @Override
    public void onFragmentCreated(Bundle savedInstanceState) {

    }

    @Override
    public void updateContent() {

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.card_front_rl) {
            photoTakeState = STATE_FRONT;
            takePicture();
        } else if (v.getId() == R.id.card_back_rl) {
            photoTakeState = STATE_BACK;
            takePicture();
        } else if (v.getId() == R.id.person_photo_rl) {
            photoTakeState = STATE_PERSON;
            takePicture();
        } else if (v.getId() == R.id.next_step_tv) {
            validData();
        } else if (v.getId() == R.id.compare_tv) {
            compareImg();
        }
    }

    private void compareImg() {
        List<File> files = new ArrayList<>();
        if (TextUtils.isEmpty(personalImg1Path)) {
            ToastMaker.showToastShort(R.string.card_valid_front_tip);
            return;
        }
        files.add(new File(personalImg1Path));
        if (TextUtils.isEmpty(personalImg3Path)) {
            ToastMaker.showToastShort(R.string.card_valid_person_tip);
            return;
        }
        files.add(new File(personalImg3Path));
        showProgressDialog("正在进行身份比对，请稍后...");
        API.getInstance().getUserApi().piccheck(this, files, new JsonCallBack<PicCheckResult>() {
            @Override
            public void onSuccess(PicCheckResult checkResult, Call call, Response response) {
                hideProgressDialog();

                if (checkResult != null && checkResult.data != null) {
                    compareScore = checkResult.data.score;
                    float clique = checkResult.data.clique;

                    if (compareScore >= clique) {
                        compareScore = 1.f;
                        compareSuccess = true;
                        showAuthSuccessDialog();
                    } else {
                        showAuthFailDialog((int) (compareScore*100));
                    }
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                hideProgressDialog();
            }
        });
    }


    private void validData() {
        String name = nameEt.getEditableText().toString();
        if (TextUtils.isEmpty(name)) {
            ToastMaker.showToastLong(R.string.input_user_name);
            return;
        }

        IdCardUtil cardUtil = new IdCardUtil(identityCardEt.getEditableText().toString());
        if (cardUtil.isCorrect() == 0) {
            AppPreferences.putString(Constants.CURRENT_CARD_ID, identityCardEt.getEditableText().toString());



            if (TextUtils.isEmpty(personalImg1Path)) {
                ToastMaker.showToastShort(R.string.card_valid_front_tip);
                return;
            }

            if (TextUtils.isEmpty(personalImg2Path)) {
                ToastMaker.showToastShort(R.string.card_valid_back_tip);
                return;
            }

            if (TextUtils.isEmpty(personalImg3Path)) {
                ToastMaker.showToastShort(R.string.card_valid_person_tip);
                return;
            }

            if (!compareSuccess) {
                ToastMaker.showToastShort(R.string.compare_first);
                return;
            }

            List<File> files = new ArrayList<>();
            files.add(new File(personalImg1Path));
            files.add(new File(personalImg2Path));
            files.add(new File(personalImg3Path));

            showProgressDialog("正在上传，请稍后");
            API.getInstance().getUserApi().valid(this, identityCardEt.getEditableText().toString(),
                    name,
                    compareScore,
                    AppPreferences.getString(Constants.ADDRESS, ""),
                    files, new JsonCallBack<BaseResult>() {
                        @Override
                        public void onSuccess(BaseResult baseResult, Call call, Response response) {
                            hideProgressDialog();
                            if(baseResult.status == 200){
                                gotoNextStep();
                            }else{
                                ToastMaker.showToastShort("上传失败，请稍后再试~" + baseResult.status);
                            }

                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);

                            hideProgressDialog();
                        }
                    });
        } else {
            ToastMaker.showToastLong(cardUtil.getErrMsg());
        }
    }

    private void takePicture() {
        if (headphotoManager != null) {
            headphotoManager.showChangeHeadPhotoDialog();
        }
    }


    private void showAuthFailDialog(int score) {
        View view = View.inflate(getActivity(), R.layout.dialog_auth_fail, null);

        final Dialog dlg = MMAlert.showViewAlertCommon(getActivity(), view);
        String str = String.format("很遗憾，身份比对失败\n，对比相似度%d%%", score);
        TextView resultTv = view.findViewById(R.id.result_tv);
        resultTv.setText(str);

        ImageView leftImg = view.findViewById(R.id.left_img);
        ImageView rightImg = view.findViewById(R.id.right_img);
        ImageManager.loadImage(YunloanApp.getInstance(), leftImg, personalImg1Path);
        ImageManager.loadImage(YunloanApp.getInstance(), rightImg, personalImg3Path);
        Button authFailBtn = view.findViewById(R.id.auth_fail_btn);
        Button authPassBtn = view.findViewById(R.id.auth_pass_btn);

        authPassBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                compareSuccess = true;
                dlg.dismiss();
            }
        });

        authFailBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dlg.dismiss();
            }
        });

        dlg.setCanceledOnTouchOutside(false);
        dlg.show();
    }

    private void showAuthSuccessDialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_auth_success, null);
        final Dialog dlg = MMAlert.showViewAlertCommon(getActivity(), view);
        dlg.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (headphotoManager != null) {
            headphotoManager.onActivityResult(requestCode, resultCode, data);
        }
    }


    private void gotoNextStep() {
        //进入拍摄视频页面
//        ((CaseActivity) getActivity()).select(INDEX_SIGN);
        if (isAdded()){
            getActivity().finish();
        }
    }


    public void setData(CaseEntity caseEntity) {
        mCaseEntity = caseEntity;
    }
}
